<template>
  <div class="login-form-content">
    <div class="login" v-if="route.query.loginType == '0'">
      <el-form
        class="login-form"
        status-icon
        :rules="loginRules"
        ref="loginFormRef"
        :model="loginForm"
        label-width="0"
        id="loginFormId"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            auto-complete="off"
            :prefix-icon="PhoneFilled"
            :maxlength="11"
            placeholder="手机号码"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="code" class="login-code">
          <el-input
            class="code-input"
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
          >
          </el-input>
          <div
            class="code-content grid-content ep-bg-purple"
            :style="codeBtnDisabled ? 'cursor:not-allowed' : ''"
          >
            <span :style="codeBtnDisabled ? 'pointer-events:none;' : ''" @click="handleSendCode">{{
              codeBtnText
            }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin(loginFormRef)" class="login-submit"
            >登 录
          </el-button>
          <el-button
            type="success"
            class="back-btn"
            plain
            style="margin-left: 0"
            @click="router.back()"
            >返 回</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="new-login" v-else>
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formDataRef"
        label-position="top"
        style="width: 90%; margin-top: 50px"
      >
        <!-- 姓名 -->
        <el-form-item label="姓名:" prop="name" required>
          <el-input v-model="formData.name" placeholder="请输入姓名" @blur="refreshCodeBtnText" />
        </el-form-item>

        <!-- 姓名缩写 -->
<!--        <el-form-item label="姓名缩写:" prop="nameSx">-->
<!--          <el-input v-model="formData.nameSx" placeholder="请输入姓名缩写" />-->
<!--        </el-form-item>-->

        <!-- 出生日期 -->
        <el-form-item label="出生日期:" prop="birthDate">
          <el-date-picker
            v-model="formData.birthDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            format="YYYY年MM月DD日"
          />
          <div class="form-tips">格式：xxxx年xx月xx日</div>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" :maxlength="11" />
          <div class="form-tips red">使用短信/微信通知和二维码录入时必填</div>
        </el-form-item>

        <!-- 手机验证码 -->
        <el-form-item label="手机验证码:" prop="smsCode">
          <el-input-group style="width: 100%; display: flex">
            <el-input v-model="formData.smsCode" placeholder="请输入验证码" />
            <el-button class="get-code-btn" type="primary">获取</el-button>
          </el-input-group>
          <div class="form-tips">请输入获取的验证码</div>
        </el-form-item>

        <!-- 住院号 -->
        <el-form-item label="住院号:" prop="zyh" required>
          <el-input v-model="formData.zyh" placeholder="请输入住院号" />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="action-btns">
          <el-button class="clear-btn" @click="router.back()" icon="ArrowLeft" text
            >返 回</el-button
          >
          <el-button class="clear-btn" @click="handleClear">清 除</el-button>
          <el-button type="primary" @click="handleSubmit(formDataRef)">保 存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
// import pinyin from 'pinyin';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTrialDetail } from '@/api/trial/trial';
import { createByPhone, sendSmsCode,loginByPhone } from '@/api/clinicalcase/clinicalCase';
import { PhoneFilled } from '@element-plus/icons-vue';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
let formDataRef = ref();
let loginFormRef = ref();

// 表单数据
const loginForm = reactive({
  phone: '',
  code: '',
});

// 表单验证规则
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur',
    },
  ],
  // code: [
  //   { required: true, message: '请输入验证码', trigger: 'blur' },
  //   { min: 4, max: 6, message: '验证码长度为4-6位', trigger: 'blur' },
  // ],
};

const formData = reactive({
  name: '',
  nameSx: '',
  birthDate: '',
  phone: '',
  smsCode: '',
  zyh: '',
});

const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  zyh: [{ required: true, message: '请输入住院号', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
});
let trialForm = ref({});
onMounted(() => {
  if (routerQuery.value.trialId) {
    getTrialDetail(routerQuery.value.trialId).then(res => {
      trialForm.value = res.data.data;
    });
  }
});

const handleClear = () => {
  Object.keys(formData).forEach(key => (formData[key] = ''));
};
// 新建表单提交
const handleSubmit = formEl => {
  formEl.validate().then(valid => {
    formData.trial = routerQuery.value.trialId;
    formData.groupId = routerQuery.value.groupId;
    // formData.researcher = trialForm.value.researcher;
    formData.hospitalDept = trialForm.value.researchInstitution;
    if (valid) {
      createByPhone(formData)
        .then(res => {
          ElMessage.success('操作成功!');
          routerQuery.value.caseUserId = res.data.data.id;
          routerQuery.value.groupId = res.data.data.groupId;
          router.replace({
            path: '/CrfH5/FillCrf',
            query: {
              ...routerQuery.value,
            },
          });
        })
        .catch(error => {
          // window.console.console.log(error);
        });
    }
  });
};

// 验证码按钮状态
const codeBtnText = ref('获取验证码');
const codeBtnDisabled = ref(false);

// 获取验证码处理
const handleSendCode = () => {
  sendSmsCode(loginForm.phone).then(res => {
    // console.log(res);
    if (res.data.success) {
      ElMessage.success(res.data.msg);
    } else {
      ElMessage.error(res.data.msg);
    }
    // loginForm.code = res.data.data;
    let seconds = 60;
    codeBtnDisabled.value = true;
    const timer = setInterval(() => {
      seconds--;
      codeBtnText.value = `${seconds}秒后重发`;
      if (seconds <= 0) {
        clearInterval(timer);
        codeBtnText.value = '获取验证码';
        codeBtnDisabled.value = false;
      }
    }, 1000);
  });
};

// 登录处理
const handleLogin = async formEl => {
  // loginForm表单绑定对象
  formEl.validate().then(valid => {
    if (valid) {
      loginByPhone(loginForm.phone,loginForm.code || '123456').then(res => {
        routerQuery.value.caseUserId = res.data.data.id;
        routerQuery.value.groupId = res.data.data.groupId;
        router.replace({
          path: '/CrfH5/FillCrf',
          query: {
            ...routerQuery.value,
          },
        });
      });
    }
  });
  // await formEl.validate(valid => {
  //   if (valid) {
  //     console.log('提交数据:', form);
  //     /* 登录成功后跳入CRF填写页面 */
  //     /* router.push({
  //       path: '/CrfH5/FillCrf',
  //       query: {
  //         ...routerQuery.value,
  //       },
  //     }); */
  //   }
  // });
};
// 姓名输入框失焦事件
const refreshCodeBtnText = text => {
  console.log('这个地方是什么', text, formData.name);
  let result = '';
  // 判断输入类型
  if (/^[\u4e00-\u9fa5]+$/.test(formData.name)) {
    // 输入的是中文
    for (let i = 0; i < formData.name.length; i++) {
      // 获取拼音的首字母
      result += pinyin(formData.name[i])[0][0].toUpperCase();
    }
  } else if (/^[A-Za-z]+$/.test(formData.name)) {
    // 输入的是英文
    result = formData.name[0].toUpperCase();
  } else if (/^\d+$/.test(formData.name)) {
    // 输入的是数字
    result = formData.name;
  } else {
    result = '无效输入';
  }
  console.log('结果', result);
};

// 返回处理
const handleBack = () => {
  // 返回上一页或关闭弹窗等逻辑
  console.log('返回操作');
};
</script>
<style scoped lang="scss">
.login-form-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}
.new-login {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-form {
  width: 90%;
  padding: 0;
  ::v-deep .el-form-item {
    margin-bottom: 45px;
  }
  ::v-deep .el-input__inner {
    font-size: 16px;
  }
  ::v-deep .el-input__wrapper {
    height: 40px;
    border: 1px solid #909090;
  }
  .login-password {
    margin-bottom: 0;
  }
  .forget-password {
    width: 97%;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #2c77f1;
    font-size: 14px;
    cursor: pointer;
  }
  .code-btn {
    ::v-deep .el-input__inner {
      text-align: center;
      color: #2c77f1;
    }
  }
  .login-code {
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;
    }
    .code-input {
      width: 60%;
    }
  }
  .code-content {
    width: 30%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #2c77f1;
    border-radius: 20px;
    border: 1px solid #909090;
    cursor: pointer;
  }
  .login-submit {
    height: 50px;
    border-radius: 20px;
    margin-top: 45px;
    background-color: #3844d6;
  }
  .back-btn {
    width: 100%;
    height: 50px;
    border-radius: 20px;
    margin-top: 45px;
    font-size: 18px;
  }
  .hint-text {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: black;
    font-size: 14px;
  }
}
.back-btn {
  margin-bottom: 20px;
}

.form-tips {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.red {
  color: #f56c6c;
}

.action-btns {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: space-between;
  }
}

.clear-btn {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.get-code-btn {
  width: 80px;
}
</style>
